package com.bang.study.aggs;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalDateHistogram;
import org.elasticsearch.search.aggregations.metrics.cardinality.InternalCardinality;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.util.List;

/**
 * @ClassName: MuchAggsSearch
 * @author: BANG
 * @Date: 2020/01/15 16:57
 * @Version: 1.0
 * @Modified By:
 * @Desc: TODO
 *
 * GET /tvs/sales/_search
 * {
 *     "size" : 0,
 *     "aggs" : {
 *         "distinct_brand" : {
 *             "cardinality" : {
 *               "field" : "brand",
 *               "precision_threshold" : 100
 *             }
 *         }
 *     }
 * }
 */
public class Precision_thresholdAggsSearch {


    public static void main(String[] args) throws Exception {
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .put("client.transport.sniff", true)
                .build();

        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)
        );

        SearchResponse searchResponse = client.prepareSearch("tvs").setTypes("sales")
                .addAggregation(AggregationBuilders.cardinality("distinct_brand")
                        .field("brand")
                        .precisionThreshold(100L)
                        )
                .setSize(0)
                .get();

        InternalCardinality distinct_brand = searchResponse.getAggregations().get("distinct_brand");
        String valueAsString = distinct_brand.getValueAsString();
        System.err.println("distinct_brand "+valueAsString);
        client.close();

    }
}
